﻿using BulkUploadGovernanceFiles.Models;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;

namespace BulkUploadGovernanceFiles
{
    public class GovernancePdfProfileMetadataRepository
    {
        private readonly MongoCollection<GovernancePdfProfileMetadata> _governancePdfProfileMetadataCollection;

        public GovernancePdfProfileMetadataRepository()
        {
            var clientPlatformConnectionString = ConfigManager.GovernanceInputFile.ConnectionString;
            var mongoClient = new MongoClient(clientPlatformConnectionString);
            var server = mongoClient.GetServer();
            var database = server.GetDatabase(ConfigManager.GovernanceInputFile.DataBaseName);

            _governancePdfProfileMetadataCollection = database.GetCollection<GovernancePdfProfileMetadata>("GovernancePdfProfileMetadata");
        }

        public void Insert(GovernancePdfProfileMetadata governancePdfProfileMetadata, GovernancePdfType type)
        {
            _governancePdfProfileMetadataCollection.Insert(new GovernancePdfProfileMetadata
            {
                Id = governancePdfProfileMetadata.Id,
                FileId = governancePdfProfileMetadata.FileId,
                CompanyId = governancePdfProfileMetadata.CompanyId,
                OperationType = UpdateOperationType.Created,
                GovernancePdfType = type,
                LastOperationUserName = governancePdfProfileMetadata.LastOperationUserName,
                LastOperationDateTime = DateTime.UtcNow,
                FileName = governancePdfProfileMetadata.FileName,
            });
        }

        public List<GovernancePdfProfileMetadata> GetByCompanyIdAndGovernancePdfType(Guid companyId, GovernancePdfType governancePdfType)
        {
            return _governancePdfProfileMetadataCollection.FindAllAs<GovernancePdfProfileMetadata>().Where(x => x.CompanyId == companyId).Where(x=>x.GovernancePdfType == governancePdfType).ToList();
        }

        public void RemoveByComapnyId(Guid companyId, GovernancePdfType governancePdfType)
        {
            var clauses = new[] { Query.EQ("CompanyId", companyId), Query.EQ("GovernancePdfType", governancePdfType.ToString()) };
            var query = Query.And(clauses);
            
            _governancePdfProfileMetadataCollection.Remove(query);
        }

        public void RemoveAll(GovernancePdfType type)
        {
            _governancePdfProfileMetadataCollection.Remove(new QueryDocument("GovernancePdfType", type.ToString()));
        }
    }
}
